package com.shop.front.interceptor;

import com.shop.domain.user.User;
import com.shop.front.service.user.UserService;
import com.shop.web.context.WebContext;
import com.shop.web.exception.NeedLoginException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class UserInterceptor implements HandlerInterceptor {


    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        // 维护中
        //if(true) throw new NeedLoginException();

        User user = userService.authUserIdByAccessToken(WebContext.getAccessToken());
        if (null == user) {
            throw new NeedLoginException();
        }
        WebContext.setPrincipal(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        WebContext.clearThreadLocals();
    }

}
